/**
 * 
 */
package com.zoiz.dbutils;

import java.io.Serializable;
import java.util.List;


import com.zoiz.dbutils.QueryHelper.WrappedStatement;
import com.zoiz.plus.extend.StringUtils;

/**
 * @author administrator
 * 
 */
public abstract class Model implements Serializable {
	private static final long serialVersionUID = 1L;
	protected static final String _AND=" AND ";

	//count
	protected static long count(Class<?> clazz){
		return QueryHelper.stat("SELECT COUNT(1) FROM "+clazz.getSimpleName().toUpperCase());
	}
	// count by
	protected static Long count(Class<?> clazz, String query, Object... params) {
		return QueryHelper.stat(
				"select count(1) from "
						+ clazz.getSimpleName().toLowerCase()
						+ (StringUtils.isBlank(query) ? ""
								: (" where " + query)), params);
	}		
	// find one by id
	protected static <T extends Model> T findById(Class<T> clazz, Object id) {
		return findOneBy(clazz, "id=?", id);
	}

	// find one by
	protected static <T extends Model> T findOneBy(Class<T> clazz, String query, Object... params) {
		List<T> result = findAllBy(clazz, query, params);
		if (result != null && result.size() > 0)
			return result.get(0);
		return null;
	}

	// find by query
	protected static <T extends Model> List<T> findAllBy(Class<T> clazz, String query, Object... params) {
		boolean generateQuery=true;
		if(query!=null && query.toUpperCase().trim().startsWith("SELECT")){
			generateQuery=false;
		}
		return QueryHelper.query(clazz, generateQuery?"SELECT * FROM " + clazz.getSimpleName().toLowerCase() + (StringUtils.isBlank(query) ? "" : (" WHERE " + query)):query, params);
	}

	// delete by id
	protected static int deleteById(Class<?> clazz, Object id) {
		return deleteBy(clazz, "id=?", id);
	}

	// delete by
	protected static int deleteBy(Class<?> clazz, String query, Object... params) {
		return QueryHelper.update("DELETE FROM " + clazz.getSimpleName().toUpperCase() + (StringUtils.isBlank(query) ? "" : (" where " + query)), params);
	}

	// delete all
	protected static int deleteAll(Class<?> clazz) {
		return deleteBy(clazz, null);
	}
	protected long insert(WrappedStatement ws){
		return QueryHelper.insert(ws.getSql(), ws.getParams().toArray());
	}
	protected int update(WrappedStatement ws){
		return QueryHelper.update(ws.getSql(), ws.getParams().toArray());
	}
}
